<?php
namespace app\common\utils;

use app\admin\model\Ordderdistributionaddress;
use app\admin\model\Printer;
use app\admin\model\Shop;
use think\Log;

header("Content-type: text/html; charset=utf-8");
define('USER', '2905627412@qq.com');  //*必填*：飞鹅云后台注册账号
define('UKEY', 'cN4PzMjKT5tDzjYr');  //*必填*: 飞鹅云后台注册账号后生成的UKEY 【备注：这不是填打印机的KEY】
define('SN', '522560533');      //*必填*：打印机编号，必须要在管理后台里添加打印机或调用API接口添加之后，才能调用API

//以下参数不需要修改
define('IP', 'api.feieyun.cn');      //接口IP或域名
define('PORT', 80);            //接口IP端口
define('PATH', '/Api/Open/');    //接口路径
class FeiUtil
{

    /**
     * @param $order
     * @param int $A
     * @param int $B
     * @param int $C
     * @param int $D
     * @return string
     * 小票打印 不能贴
     */
    public function printerOrder($order,$sn, $A = 14, $B = 6, $C = 3, $D = 6)
    {
        $shop_name = '尼克食惠';
        $orderInfo = '<CB>'.$shop_name.'</CB><BR>';
        $orderInfo .= '<CB>订单编号：'.$order['order_no'].'</CB><BR>';
        $orderInfo .= '名称           单价  数量 金额<BR>';
        $orderInfo .= '--------------------------------<BR>';
        foreach ($order->ordergoods as $k5 => $v5) {
            $name = $v5['goods_name'];
            $price = $v5['goods_money'];
            $num = $v5['num'];
            $prices = $v5['money'];
            $kw3 = '';
            $kw1 = '';
            $kw2 = '';
            $kw4 = '';
            $str = $name;
            $blankNum = $A;//名称控制为14个字节
            $lan = mb_strlen($str,'utf-8');
            $m = 0;
            $j=1;
            $blankNum++;
            $result = array();
            if(strlen($price) < $B){
                $k1 = $B - strlen($price);
                for($q=0;$q<$k1;$q++){
                    $kw1 .= ' ';
                }
                $price = $price.$kw1;
            }
            if(strlen($num) < $C){
                $k2 = $C - strlen($num);
                for($q=0;$q<$k2;$q++){
                    $kw2 .= ' ';
                }
                $num = $num.$kw2;
            }
            if(strlen($prices) < $D){
                $k3 = $D - strlen($prices);
                for($q=0;$q<$k3;$q++){
                    $kw4 .= ' ';
                }
                $prices = $prices.$kw4;
            }

            for ($i=0;$i<$lan;$i++){
                $new = mb_substr($str,$m,$j,'utf-8');
                $j++;
                if(mb_strwidth($new,'utf-8')<$blankNum) {
                    if($m+$j>$lan) {
                        $m = $m+$j;
                        $tail = $new;
                        $lenght = iconv("UTF-8", "GBK//IGNORE", $new);
                        $k = $A - strlen($lenght);
                        for($q=0;$q<$k;$q++){
                            $kw3 .= ' ';
                        }
                        if($m==$j){
                            $tail .= $kw3.' '.$price.' '.$num.' '.$prices;
                        }else{
                            $tail .= $kw3.'<BR>';
                        }
                        break;
                    }else{
                        $next_new = mb_substr($str,$m,$j,'utf-8');
                        if(mb_strwidth($next_new,'utf-8')<$blankNum) continue;
                        else{
                            $m = $i+1;
                            $result[] = $new;
                            $j=1;
                        }
                    }
                }
            }

            $head = '';
            foreach ($result as $key=>$value) {
                if($key < 1){
                    $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value);
                    $v_lenght = strlen($v_lenght);
                    if($v_lenght == 13) $value = $value." ";
                    $head .= $value.' '.$price.' '.$num.' '.$prices;
                }else{
                    $head .= $value.'<BR>';
                }
            }
            $orderInfo .= $head.$tail;
        }
        $address = json_decode($order['address_info'],true);
        $orderInfo .= '--------------------------------<BR>';
        $orderInfo .= '总数量：<B>' . $order['goods_num'] . '</B><BR>';
        $orderInfo .= '合计：<B>' . $order['money'] . '元</B><BR>';

        $orderInfo .= '联系人：' . $address['username'] . '</B><BR>';
        //手机号前7位*号代替
//        $orderInfo .= '联系电话：' . substr_replace($address['mobile'],'****',3,4) . '</B><BR>';
        $orderInfo .= '联系电话：' . substr_replace($address['mobile'],'*******',0,7) . '</B><BR>';
        $orderInfo .= '送货地址：' . $address['address'] . '宿舍号'.$address['dorm'].'</B><BR>';
        $orderInfo .= '下单时间：' . date('Y-m-d H:i:s', $order['createtime']) . '<BR>';
//        echo $orderInfo;
//        exit;
        return $this->printMsg($sn,USER,UKEY,$orderInfo,1);
    }
    /**
     * 标签打印 可以粘贴
     * 地址订单打印
     */
    public function printLabel2($order,$sn)
    {

        $addressL = Ordderdistributionaddress::where('order_no',$order['order_no'])->select();
        foreach ($addressL as $k=>$address){
            $content = "<DIRECTION>1</DIRECTION>";//设定打印时出纸和打印字体的方向，n 0 或 1，每次设备重启后都会初始化为 0 值设置，1：正向出纸，0：反向出纸，

            $content .= "<TEXT x='320' y='20' font='12' w='1' h='2' r='90'>   ".$address['shou_address']."  ".$address['dorm']."</TEXT>";
            $content .= "<TEXT x='270' y='20' font='12' w='1' h='2' r='90'>   下单时间：".date('Y-m-d H:i:s',$order['createtime'])."     取件码  ".$address['claim_code']."</TEXT>";
            $content .= "<TEXT x='190' y='20' font='12' w='1' h='2' r='90'>   ".$address['get_address']."      </TEXT>";
            $content .= "<TEXT x='110' y='20' font='12' w='1' h='2' r='90'>   ".substr_replace($address['mobile'],"*******",0,7)."       ".$address['username']."</TEXT>";
            $content .= "<QR x='70' y='380'>https://mp.weixin.qq.com/a/~v68BKFamzS0xQF023eCjpA~~</QR> ";
            $res = $this->printLabelMsg($sn, $content, 1);
            echo '<pre>';
            print_r($res);
            Log::error("地址打印订单：".$order->id);
            Log::error($res);

        }

//        return
    }

    /**
     * 标签打印 可以粘贴
     *       //    50*80标签纸   飞鹅技术 2021-01-14
     */
    public function printLabel($order,$sn)
    {
        $content = "<DIRECTION>1</DIRECTION>";//设定打印时出纸和打印字体的方向，n 0 或 1，每次设备重启后都会初始化为 0 值设置，1：正向出纸，0：反向出纸，
        $address = json_decode($order['address_info'],true);
        $content .= "<TEXT x='320' y='20' font='12' w='1' h='2' r='90'>   ".$address['address']."  ".$address['dorm']."</TEXT>";
        $content .= "<TEXT x='270' y='20' font='12' w='1' h='2' r='90'>   下单时间：".date('Y-m-d H:i:s',$order['createtime'])."</TEXT>";
        $content .= "<TEXT x='190' y='20' font='12' w='1' h='2' r='90'>   ".$order['goods_num']."件商品       ￥".$order['money']."      </TEXT>";
        $content .= "<TEXT x='110' y='20' font='12' w='1' h='2' r='90'>   ".substr_replace($address['mobile'],"*******",0,7)."       ".$address['username']."</TEXT>";
        $content .= "<QR x='70' y='350'>https://mp.weixin.qq.com/a/~v68BKFamzS0xQF023eCjpA~~</QR> ";
        return $this->printLabelMsg($sn, $content, 1);
    }

    /**
     * [批量添加打印机接口 Open_printerAddlist]
     * @param  [string] $printerContent [打印机的sn#key]
     * @return [string]                 [接口返回值]
     */
    function printerAddlist($printerContent)
    {
        $time = time();         //请求时间
        $msgInfo = array(
            'user' => USER,
            'stime' => $time,
            'sig' => signature($time),
            'apiname' => 'Open_printerAddlist',
            'printerContent' => $printerContent
        );
        $client = new HttpClient(IP, PORT);
        if (!$client->post(PATH, $msgInfo)) {
            echo 'error';
        } else {
            $result = $client->getContent();
            echo $result;
        }
    }


    /**
     * [打印订单接口 Open_printMsg]
     * @param  [string] $sn      [打印机编号sn]
     * @param  [string] $content [打印内容]
     * @param  [string] $times   [打印联数]
     * @return [string]          [接口返回值]
     */
    function printMsg($sn,$user,$ukey, $content, $times)
    {
        $time = time();         //请求时间
        $msgInfo = array(
            'user' => $user,
            'stime' => $time,
            'sig' => $this->signature($time,$ukey),
            'apiname' => 'Open_printMsg',
            'sn' => $sn,
            'content' => $content,
            'times' => $times//打印次数
        );
        $client = new FeiE(IP, PORT);
        if (!$client->post(PATH, $msgInfo)) {
            return 'error';
        } else {
            //服务器返回的JSON字符串，建议要当做日志记录起来
            return $client->getContent();
        }
    }
    function printLabelMsg2($sn, $content, $times = 1)
    {
        $url = 'http://api.feieyun.cn/Api/Open/';
        $stime = time();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, [
            'user' => USER,
            'stime' => $stime,
            'sig' => $this->signature($stime),
            'apiname' => 'Open_printLabelMsg',
            'sn' => $sn,
            'content' => $content,
            'times' => $times,
            'img' => new \CURLFile('uploads/xcx.jpg')
            /* 2.jpg  为  图片大小不能超240*240像素  设置宽高 必须为 8的倍数，支持 png 和 jpg   */

        ]);
        $headers = array('Content-Type: multipart/form-data;');//传图
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec($ch);
        curl_close($ch);
        var_dump($response);
        return $response;
    }
    /**
     * [标签机打印订单接口 Open_printLabelMsg]
     * @param  [string] $sn      [打印机编号sn]
     * @param  [string] $content [打印内容]
     * @param  [string] $times   [打印联数]
     * @return [string]          [接口返回值]
     */
    function printLabelMsg($sn, $content, $times)
    {
        $time = time();         //请求时间
        $msgInfo = array(
            'user' => USER,
            'stime' => $time,
            'sig' => $this->signature($time),
            'apiname' => 'Open_printLabelMsg',
            'sn' => $sn,
            'content' => $content,
            'times' => $times,//打印次数
//            'img' => new \CURLFile('uploads/xcx.jpg')
        );
        $client = new FeiE(IP, PORT);
        if (!$client->post(PATH, $msgInfo)) {
            return 'error';
        } else {
            //服务器返回的JSON字符串，建议要当做日志记录起来
            return $client->getContent();
        }
    }

    /**
     * [批量删除打印机 Open_printerDelList]
     * @param  [string] $snlist [打印机编号，多台打印机请用减号“-”连接起来]
     * @return [string]         [接口返回值]
     */
    function printerDelList($snlist)
    {
        $time = time();         //请求时间
        $msgInfo = array(
            'user' => USER,
            'stime' => $time,
            'sig' => signature($time),
            'apiname' => 'Open_printerDelList',
            'snlist' => $snlist
        );
        $client = new HttpClient(IP, PORT);
        if (!$client->post(PATH, $msgInfo)) {
            echo 'error';
        } else {
            $result = $client->getContent();
            echo $result;
        }
    }

    /**
     * [修改打印机信息接口 Open_printerEdit]
     * @param  [string] $sn       [打印机编号]
     * @param  [string] $name     [打印机备注名称]
     * @param  [string] $phonenum [打印机流量卡号码,可以不传参,但是不能为空字符串]
     * @return [string]           [接口返回值]
     */
    function printerEdit($sn, $name, $phonenum)
    {
        $time = time();         //请求时间
        $msgInfo = array(
            'user' => USER,
            'stime' => $time,
            'sig' => signature($time),
            'apiname' => 'Open_printerEdit',
            'sn' => $sn,
            'name' => $name,
            'phonenum' => $phonenum
        );
        $client = new HttpClient(IP, PORT);
        if (!$client->post(PATH, $msgInfo)) {
            echo 'error';
        } else {
            $result = $client->getContent();
            echo $result;
        }
    }


    /**
     * [清空待打印订单接口 Open_delPrinterSqs]
     * @param  [string] $sn [打印机编号]
     * @return [string]     [接口返回值]
     */
    function delPrinterSqs($sn)
    {
        $time = time();         //请求时间
        $msgInfo = array(
            'user' => USER,
            'stime' => $time,
            'sig' => signature($time),
            'apiname' => 'Open_delPrinterSqs',
            'sn' => $sn
        );
        $client = new HttpClient(IP, PORT);
        if (!$client->post(PATH, $msgInfo)) {
            echo 'error';
        } else {
            $result = $client->getContent();
            echo $result;
        }
    }

    /**
     * [查询订单是否打印成功接口 Open_queryOrderState]
     * @param  [string] $orderid [调用打印机接口成功后,服务器返回的JSON中的编号 例如：123456789_20190919163739_95385649]
     * @return [string]          [接口返回值]
     */
    function queryOrderState($orderid)
    {
        $time = time();         //请求时间
        $msgInfo = array(
            'user' => USER,
            'stime' => $time,
            'sig' => signature($time),
            'apiname' => 'Open_queryOrderState',
            'orderid' => $orderid
        );
        $client = new HttpClient(IP, PORT);
        if (!$client->post(PATH, $msgInfo)) {
            echo 'error';
        } else {
            $result = $client->getContent();
            echo $result;
        }
    }

    /**
     * [查询指定打印机某天的订单统计数接口 Open_queryOrderInfoByDate]
     * @param  [string] $sn   [打印机的编号]
     * @param  [string] $date [查询日期，格式YY-MM-DD，如：2019-09-20]
     * @return [string]       [接口返回值]
     */
    function queryOrderInfoByDate($sn, $date)
    {
        $time = time();         //请求时间
        $msgInfo = array(
            'user' => USER,
            'stime' => $time,
            'sig' => signature($time),
            'apiname' => 'Open_queryOrderInfoByDate',
            'sn' => $sn,
            'date' => $date
        );
        $client = new HttpClient(IP, PORT);
        if (!$client->post(PATH, $msgInfo)) {
            echo 'error';
        } else {
            $result = $client->getContent();
            echo $result;
        }
    }

    /**
     * [获取某台打印机状态接口 Open_queryPrinterStatus]
     * @param  [string] $sn [打印机编号]
     * @return [string]     [接口返回值]
     */
    function queryPrinterStatus($sn)
    {
        $time = time();         //请求时间
        $msgInfo = array(
            'user' => USER,
            'stime' => $time,
            'sig' => signature($time),
            'apiname' => 'Open_queryPrinterStatus',
            'sn' => $sn
        );
        $client = new HttpClient(IP, PORT);
        if (!$client->post(PATH, $msgInfo)) {
            echo 'error';
        } else {
            $result = $client->getContent();
            echo $result;
        }
    }

    /**
     * [signature 生成签名]
     * @param  [string] $time [当前UNIX时间戳，10位，精确到秒]
     * @return [string]       [接口返回值]
     */
    function signature($time)
    {
        return sha1(USER . UKEY . $time);//公共参数，请求公钥
    }
}


?>
